import dataPreferences from '@ohos.data.preferences';
import hilog from '@ohos.hilog';
import {PREFERENCES_NAME} from '../common/Constant'
var preference: dataPreferences.Preferences = null;
export async function init(context){
  try {
    preference = await dataPreferences.getPreferences(context, PREFERENCES_NAME);
  } catch (err) {
    hilog.error(0x0000, 'testTag', '%{public}s', 'init failed');
  }
}


/**
 * 获取数据
 */
export async function getData(key:string,context){
  if(preference==null){
   await init(context)
  }
  let valueData = '';

  try {
    valueData = <string> await preference.get(key, '');
  } catch (err) {
    hilog.error(0x0000, 'testTag', '%{public}s', 'get failed');
  }

  return valueData;
}
/**
 * 写入数据
 */
export async function putData(key:string,value:string,context){
  if(preference==null){
    await   init(context)
  }
  try {
    preference.put(key,value);
    preference.flush();
  } catch (err) {
    hilog.error(0x0000, 'testTag', '%{public}s', 'put failed');
  }
}
/**
 * 删除数据
 */
export async function deleteData(key:string,context){
  if(preference==null){
    await init(context)
  }
  try {
    preference.delete(key);
  } catch (err) {
    hilog.error(0x0000, 'testTag', '%{public}s', 'delete failed');
  }
}
/**
 * 持久化数据
 */
export async function flushData(context){
  if(preference==null){
    await init(context)
  }
  try {
    preference.flush();
  } catch (err) {
    hilog.error(0x0000, 'testTag', '%{public}s', 'flush failed');
  }
}